#ifndef QT_MODBUS_HELPER_H
#define QT_MODBUS_HELPER_H

#include <QMap>
#include <QModbusClient>
#include <QModbusDataUnit>
#include <QModbusReply>
#include <QModbusRtuSerialMaster>
#include <QModbusTcpClient>
#include <QMutex>
#include <QObject>
#include <QSerialPort>
#include <QSharedPointer>
#include <QTimer>
#include <QtPromise>

enum MB_DATAORDER { MB_ABCD, MB_BADC, MB_CDAB, MB_DCBA };
// 共享设备管理器
struct SharedModbusDevice {
    QSharedPointer<QModbusClient> device;
    QMutex* operationMutex;
    int refCount;
    QString identifier;  // 用于识别连接 (如 "rtu:/dev/ttyS0:38400" 或 "tcp:192.168.1.1:502")

    SharedModbusDevice(QModbusClient* dev, const QString& id)
        : device(dev), operationMutex(new QMutex), refCount(1), identifier(id)
    {
    }

    ~SharedModbusDevice() { delete operationMutex; }
};

class ModbusHelper : public QObject
{
    Q_OBJECT

public:
    explicit ModbusHelper(QObject* parent = nullptr);
    ~ModbusHelper();

    // 基础连接功能
    bool createModbus_tcp(const QString& ipAddr, int port, int unit_id = 1);
    bool createModbus_rtu(const QString& portName, int baudRate = 38400, int slaveAddress = 1);
    QString getLastError() const { return lastError; }

    // Promise 风格的异步读写接口
    QtPromise::QPromise<QVector<quint16>> asyncRead(int addr, int count);
    QtPromise::QPromise<QVector<float>> asyncReadFloat(int addr, int count,
                                                       int order = 0);  // MB_ABCD = 0
    QtPromise::QPromise<void> asyncWrite(int addr, const QVector<quint16>& values);
    QtPromise::QPromise<void> asyncWrite(int addr, const QVector<float>& values,
                                         int order = 0);  // MB_ABCD = 0
    // 数据转换辅助函数
    QVector<quint16> floatsToRegisters(const QVector<float>& values, int order = 0);
    QVector<float> registersToFloats(const QVector<quint16>& registers, int order = 0);

signals:
    void errorOccurred(const QString& errorMessage);
    void commSuccess();

private slots:
    void onModbusStateChanged(QModbusDevice::State state);
    void onModbusErrorOccurred(QModbusDevice::Error error);

private:
    QSharedPointer<SharedModbusDevice> sharedDevice;
    QString lastError;
    int currentUnitId;
    bool isOwnedDevice;  // 标记是否为TCP设备(独占)还是RTU设备(共享)

    // 静态设备管理器
    static QMap<QString, QSharedPointer<SharedModbusDevice>> s_sharedDevices;
    static QMutex s_deviceMapMutex;

    void setError(const QString& error);
    bool connectToDevice();
    void disconnectFromDevice();

    // 获取或创建共享设备
    QSharedPointer<SharedModbusDevice> getOrCreateSharedDevice(
        const QString& identifier, std::function<QModbusClient*()> deviceCreator);

    // 获取当前modbus设备指针
    QModbusClient* getModbusDevice() const;
};

#endif  // QT_MODBUS_HELPER_H